package com.kehutong.admin.controler;

import com.kehutong.admin.entity.Menu;
import com.kehutong.admin.entity.MenuRecord;
import com.kehutong.admin.service.UserHelper;
import com.kehutong.common.util.Token;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.Objects;
import org.coraframework.util.time.TimeUtil;

import java.util.List;
import java.util.Set;

@MvcAction
@ReqMapping("/admin/menu/record")
public class MenuRecordController {

	@Inject
    private JdbcSession jdbcSession;
	@Inject
	private UserHelper userHelper;

	@ReqMapping("/list")
	public Object list(Token token) throws Exception {
		// 初始化能够看见的菜单数据
		init(token);

		// 根据角色 获取能够访问的菜单数据
		Set<String> ids = userHelper.getTopMenuIds(token.getRoles());
		List<MenuRecord> list = jdbcSession.findArray(MenuRecord.class)
				.eq("userId", token.getUuid())
				.in("menuId", ids)
				.noEq("menuId","04d32d1188cc467eb7a6f363bb23760a")
				.order("accessTime", "desc")
				.exe();

		list.forEach(item -> {
			item.setMenu(Pool.get(Menu.class, item.getMenuId()));
		});

		return list;
	}

	private void init(Token token) throws Exception {
		Set<String> ids = userHelper.getTopMenuIds(token.getRoles());

		ids.forEach(id -> {
			MenuRecord record = jdbcSession.findOne(MenuRecord.class)
					.eq("userId", token.getUuid())
					.eq("menuId", id)
					.exe();
			if(Objects.isNull(record)){
				record = Pool.newInstance(MenuRecord.class);
				record.setMenuId(id);
				record.setUserId(token.getUuid());
				record.setAccessTime(null);
				jdbcSession.insert(record);
			}
		});
	}

    @ReqMapping("/updateAccessTime")
    public Object updateAccessTime(Token token, JSONObject jsonObject) {
    	MenuRecord record = jdbcSession.findOne(MenuRecord.class)
				.eq("userId", token.getUuid())
				.eq(jsonObject, "menuId")
				.exe();

    	record.setAccessTime(TimeUtil.timestamp());
    	jdbcSession.updateById(record);

    	return Result.success();
    }
	
}
